﻿using DemoWin.USBDriver;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DemoWin
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        public HidCommonHelper hid = new HidCommonHelper();
        public const ushort VID = 0x28E9;   //固定值 厂商ID（Vendor ID，简称VID）
        public const ushort PID = 0x128A;   //固定值 产品ID（Product ID，简称PID）
        private void frmMain_Load(object sender, EventArgs e)
        {
            gbxBtn.Enabled = false;
            hid.HidInitial(VID, PID, ReceiveData, ConnectedFunc);
        }

        /// <summary>
        /// 连接状态
        /// </summary>
        bool bConn = false;

        /// <summary>
        /// 连接状态
        /// </summary>
        /// <param name="isConnected"></param>
        private void ConnectedFunc(bool isConnected)
        {
            bConn = isConnected;
            lblState.Text = bConn ? "连接成功" : "连接断开";
            PrintOriginal($"{DateTime.Now.ToLongTimeString()} {lblState.Text}\r\n");

            gbxBtn.Enabled = bConn;
        }

        /// <summary>
        /// 接收数据
        /// </summary>
        /// <param name="datas"></param>
        private void ReceiveData(byte[] datas)
        {
            PrintOriginal($"{DateTime.Now.ToLongTimeString()} Read:\r\n\t{JConvert.BytesToHex(datas)}\r\n");

            try
            {
                if (datas == null)
                {
                    throw new Exception("接收为空");
                }
                if (datas.Length < 64)
                {
                    throw new Exception("接收长度不够");
                }
                int iSkip = 0;
                for (int i = 0; i < datas.Length; i++)
                {
                    if (datas[i] == 0xFC)
                    {
                        iSkip = i;
                        break;
                    }
                }
                byte[] bR;
                if (iSkip >= 1)
                {
                    bR = datas.Skip(iSkip).ToArray();
                }
                else
                {
                    bR = datas;
                }
                if (bR.Length < 64)
                {
                    throw new Exception($"接收长度不够,Skip:{iSkip},Length:{bR.Length}");
                }
                if (bR[0] == 0xFC)
                {
                    SCD read = new SCD(bR);
                    switch (read.CMD)
                    {
                        case "03":
                            Show03(read);
                            break;
                        case "04":
                            Show04(read);
                            break;
                        case "07":
                            Show07(read);
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    throw new Exception($"接收命令码错误");
                }
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }

        private void btnReadDT_Click(object sender, EventArgs e)
        {
            Send03();
        }
        private void Send03()
        {
            if (!bConn)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 设备已断开，请检查！\r\n");
                return;
            }

            SCD send;
            try
            {
                send = new SCD("FA", "03", "");
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 读设备时间,发送命令:\r\n\t{send.HEX}\r\n");
                hid.SendBytes(send.BYTES);
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }
        private void Show03(SCD read)
        {
            try
            {
                DateTime dt = new DateTime(2000 + read.BYTES[6], read.BYTES[7], read.BYTES[8], read.BYTES[9], read.BYTES[10], read.BYTES[11]);

                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 读设备时间,成功:{dt}\r\n");
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }

        private void btnSendDT_Click(object sender, EventArgs e)
        {
            Send04();
        }
        private void Send04()
        {
            if (!bConn)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 设备已断开，请检查！\r\n");
                return;
            }

            SCD send;
            try
            {
                string ss = JConvert.BytesToHex(
                        new byte[6]
                        {
                                    (byte)(DateTime.Now.Year-2000),
                                    (byte)DateTime.Now.Month,
                                    (byte)DateTime.Now.Day,
                                    (byte)DateTime.Now.Hour,
                                    (byte)DateTime.Now.Minute,
                                    (byte)DateTime.Now.Second
                        });
                send = new SCD("FA", "04", ss);
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 写设备时间,发送命令:\r\n\t{send.HEX}\r\n");
                hid.SendBytes(send.BYTES);
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }
        private void Show04(SCD read)
        {
            try
            {
                if (read.DATA.Substring(0, 2) == "01")
                {
                    PrintOriginal($"{DateTime.Now.ToLongTimeString()} 写设备时间,成功\r\n");
                }
                else
                {
                    PrintOriginal($"{DateTime.Now.ToLongTimeString()} 写设备时间,失败,code{read.DATA.Substring(0, 2)}\r\n");
                }
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }

        private void btnRead07_Click(object sender, EventArgs e)
        {
            Send07();
        }

        private void Send07()
        {
            if (!bConn)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 设备已断开，请检查！\r\n");
                return;
            }

            SCD send;
            try
            {
                send = new SCD("FA", "07", "");
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 读设备,发送命令:\r\n\t{send.HEX}\r\n");
                hid.SendBytes(send.BYTES);
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }
        private void Show07(SCD read)
        {
            try
            {
                //软件版本(2字节) + 硬件版本(2字节)
                try
                {
                    PrintOriginal($"  软件版本:{read.DATA.Substring(0, 2).ToInt()}.{read.DATA.Substring(2, 2).ToInt()}\r\n");
                }
                catch
                {
                    PrintOriginal($"  软件版本:{read.DATA.Substring(0, 4)}\r\n");
                }
                try
                {
                    PrintOriginal($"  硬件版本:{read.DATA.Substring(4, 2).ToInt()}.{read.DATA.Substring(6, 2).ToInt()}\r\n");
                }
                catch
                {
                    PrintOriginal($"  硬件版本:{read.DATA.Substring(4, 4)}\r\n");
                }
                //+ 上次联机时间(6字节) + 最近的开始记录时间(6字节)
                try
                {
                    DateTime dt = new DateTime(2000 + read.BYTES[10], read.BYTES[11], read.BYTES[12], read.BYTES[13], read.BYTES[14], read.BYTES[15]);
                    PrintOriginal($"  上次联机时间:{dt.ToString("yyyy-MM-dd HH:mm:ss")}\r\n");
                }
                catch
                {
                    PrintOriginal($"  上次联机时间:{read.DATA.Substring(8, 12)}\r\n");
                }
                try
                {
                    DateTime dt = new DateTime(2000 + read.BYTES[16], read.BYTES[17], read.BYTES[18], read.BYTES[19], read.BYTES[20], read.BYTES[21]);
                    PrintOriginal($"  开始记录时间:{dt.ToString("yyyy-MM-dd HH:mm:ss")}\r\n");
                }
                catch
                {
                    PrintOriginal($"  开始记录时间:{read.DATA.Substring(20, 12)}\r\n");
                }
                //+ 最高温度(2字节) + 最低温度(2字节) + 最高湿度(2字节) + 最低湿度(2字节)
                PrintOriginal($"  最高温度:{((double)Convert.ToInt16(read.DATA.Substring(32, 4), 16) / 100):F2}℃\r\n");
                PrintOriginal($"  最低温度:{((double)Convert.ToInt16(read.DATA.Substring(36, 4), 16) / 100):F2}℃\r\n");
                PrintOriginal($"  最高湿度:{((double)Convert.ToInt16(read.DATA.Substring(40, 4), 16) / 100):F2}%\r\n");
                PrintOriginal($"  最低湿度:{((double)Convert.ToInt16(read.DATA.Substring(44, 4), 16) / 100):F2}%\r\n");
                //+存储的数量(第34-37位)，当前温度(38-39)，当前湿度(40-41)
                PrintOriginal($"  记录数量:{Convert.ToUInt32(read.DATA.Substring(48, 8), 16)}\r\n");
                PrintOriginal($"  当前温度:{((double)Convert.ToInt16(read.DATA.Substring(56, 4), 16) / 100):F2}℃\r\n");
                PrintOriginal($"  当前湿度:{((double)Convert.ToInt16(read.DATA.Substring(60, 4), 16) / 100):F2}%\r\n");
                //+ SN值(15字节)
                PrintOriginal($"  SN值:{Encoding.ASCII.GetString(read.BYTES, 38, 15).Replace("\0", "").Trim()}\r\n");
            }
            catch (Exception ex)
            {
                PrintOriginal($"{DateTime.Now.ToLongTimeString()} 异常:{ex}\r\n");
            }
        }

        private void PrintOriginal(string msg)
        {
            this.Invoke(new Action(() =>
            {
                txtLog.AppendText(msg);
            }));
        }
    }
}
